package com.items.blog.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.items.blog.mapper.UserInfoMapper;
import com.items.blog.model.Result;
import com.items.blog.model.UserInfo;
import com.items.blog.service.UserService;
import com.items.blog.utils.JwtUtils;
import com.items.blog.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.Constants;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    // 自动注入JavaMailSender实例

    @Autowired
    private UserService userService;


    //企业标准(建议):
    //常量定义: key: 全部大写, 单词之间使用下划线分割  value: 通常是小写, 以下划线分割
    private static final String KAPTCHA_SESSION_KEY = "HOME_KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "HOME_KAPTCHA_SESSION_DATE";
    //验证码的有效时间:ms
    private static final Long SESSION_TIMEOUT = 60 * 1000L;
    //验证成功: true
    //验证失败: false


    /**
     * 注册账号
     *
     *
     * */
        @PostMapping("create")
        public Map<String, Object> createAccount(UserInfo userInfo){

            return userService.createAccount(userInfo);
        }
        /**
         * 账号激活
         *
         *
         * */
        @GetMapping("activation")
        public Map<String, Object> activationAccount(String confirmCode){

            return userService.activationAccount(confirmCode);
        }



        /**
         *
         * 登录账号
         * */

    @RequestMapping("/login")
    //调用service
    public Result login(String userName, String password,String captcha,  String salt,HttpSession session){
        /**
         * 1. 参数校验
         * 2. 密码校验
         * 3. 生成token, 并返回
         */
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空");
        }
        //获取数据库中的密码
        UserInfo userInfo = userService.queryByName(userName);
        //加密获取到的密码
        String md5PWD= SecureUtil.md5(userInfo.getPassword()+userInfo.getSalt());

        if (userInfo==null || userInfo.getId()<0){
            return Result.fail("用户不存在");
        }
        if (password.equals(md5PWD)){
            return Result.fail("密码错误!");
        }
        if (!StringUtils.hasLength(captcha)){
           return Result.fail("验证码错误");
        }
        //从Session中获取验证码
        String saveCaptcha = (String)session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date)session.getAttribute(KAPTCHA_SESSION_DATE);
        //保存的验证码和输入的验证码
//        System.out.println(saveDate);
//        System.out.println(saveCaptcha+"====="+captcha);
//        //比对验证码
        if (!saveCaptcha.equals(captcha)){
            //比对日期
            return Result.fail("验证码错误，请重新输入验证码");
        }
        Map<String, Object> claim = new HashMap<>();
        claim.put("id", userInfo.getId());
        claim.put("name", userInfo.getUserName());
        String token = JwtUtils.genToken(claim);
        return Result.success(token);

    }







    /**
     * 获取登录用户的信息
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        //1. 从token中获取用户ID
        //2. 根据用户ID, 获取用户信息
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId==null){
            return null;
        }
        return userService.queryById(userId);
    }
    /**
     * 获取当前作者的信息
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if (blogId==null && blogId<0){
            return null;
        }
        return userService.getAuthorInfo(blogId);
    }

}